package BD;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class accesoDatos {
	private String host;
	private String dmbd;
	private String bd;
	private String user;
	private String pass;
	private String type;
	private String table;
	private String where;
	private String order;
	private String group;
	private Connection conexion;
	private Statement dataquery;
	private ResultSet rs;
	private int fields;
	//public String[] params;
	Map<String,String> params = new HashMap<String,String>();
	public void begin(String tipo, String tabla){
		params.clear();
		type = tipo;
		table = tabla;
	}
	public void begin(String tipo){
		params.clear();
		type = tipo;
	}
	public void setTable(String tabla){
		table = tabla;
	}
	public void setWhere(String donde){
		where = donde;
	}
	public accesoDatos(){
		//String[] ini=null;
		where="";
		order="";
		group="";
		fields=0;
		getDataConfig config = getDataConfig.getInstance();
		String []ini = config.init();
		//String [] ini = {"localhost", "root", "", "academico"}; 
		dmbd = "mysql";
		host = 	 ini[0];
		user   = ini[1];
		if (ini[2].equals("vacio"))ini[2]="";
		pass = ini[2];
		bd = ini[3];
		for (int i=0;i<4;i++){
			System.out.println(i+"="+ini[i]);
		}
		String con = "jdbc:mysql://"+host+"/"+bd;
		System.out.println("con->"+con);
		try{
			if (dmbd.equals("mysql")){
				//DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
				//String con = "jdbc:mysql://"+host+"/"+bd;
				conexion = DriverManager.getConnection (con,user,pass);
				System.out.println("Conexion Realizada!!!!");
			}
			else if (dmbd.equals("postgresql")){
				//Conexion para postgresql
			}
			params.clear();
        }
		catch (Exception e){
        	System.out.println("Error #002");
            e.printStackTrace();
        }
	}
	public void add(String data, String value){
		params.put(data, value);
		fields++;
	}
	public void add(String data){
		params.put(data, "");
		fields++;
	}
	public String[][] getArray() {
		int rowCount=0;
		try{
		while (rs.next())
		rowCount++;
		rs.beforeFirst();
		}
		catch (Exception e){
			
		}
		String getData[][] = new String[rowCount][fields];
		System.out.println("fields->"+fields);
		//getData = new String[rowCount];
		int c=0;
		//String text;
		try{
			while(rs.next()){
				for (int i=1;i<=fields;i++){
					getData[c][i-1] = rs.getString(i);
					//getData[i-1][c] = rs.getString(i);
					//text = rs.getString(0);
				}
				c++;
	        }
		}
		catch (Exception e){
        	System.out.println("Error #004");
            e.printStackTrace();
        }
		return getData;
		
	}
	@SuppressWarnings("unchecked")
	public void execute(){
		String query="";
		if (type.equals("insert")){
			String columns="", values="";
			query+="insert into "+table+" (";
			Iterator it = params.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry e = (Map.Entry)it.next();
				columns+=""+e.getKey().toString()+",";
				values+="'"+e.getValue().toString()+"',";
			}
			columns = columns.substring(0, columns.length()-1);
			values = values.substring(0, values.length()-1);
			query+=columns+") values (" +values+")";
			
		}
		else if (type.equals("update")){
			query+="update "+table+" set ";
			Iterator it = params.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry e = (Map.Entry)it.next();
				query+=e.getKey().toString()+" = ";
				query+="'"+e.getValue().toString()+"',";
				//System.out.println(e.getKey() + " " + e.getValue());
			}
			query = query.substring(0, query.length()-1);
			if (!(where.isEmpty())) query+=" where "+where;
		}
		else if (type.equals("delete")){
			//query+="delete "+table+" set ";
			query="";
			Iterator it = params.entrySet().iterator();
			while (it.hasNext()) {
				query+=" delete from "+table+" where ";
				Map.Entry e = (Map.Entry)it.next();
				query+=e.getKey().toString()+" = ";
				query+="'"+e.getValue().toString()+"';";
				//System.out.println(e.getKey() + " " + e.getValue());
			}
		}
		else if (type.equals("select")){
			query+="select ";
			Iterator it = params.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry e = (Map.Entry)it.next();
				query+=e.getKey().toString()+",";
				//query+="'"+e.getValue().toString()+"',";
				//System.out.println(e.getKey() + " " + e.getValue());
			}
			query = query.substring(0, query.length()-1);
			query+=" from "+table+" ";
			System.out.println(where);
			if (!(where.isEmpty())) query+=" where "+where;
			if (!(order.isEmpty())) query+=" order by "+order;
			if (!(group.isEmpty())) query+=" group by "+group;
			
		}
		System.out.println(query);
		try{
			dataquery = conexion.createStatement();			
			if (type.equals("select")){
				rs = dataquery.executeQuery (query);
			}
			else{
				dataquery.executeUpdate(query);
			}
			System.out.println(query);
		}
		catch (Exception e){
        	System.out.println("Error #003");
            e.printStackTrace();
        }
	}
	
}
